﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Common;
using System.Data.Services.Client;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using Microsoft.WindowsAzure.StorageClient.Tasks;
using System.Xml.Serialization;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics;
using System.Diagnostics;

namespace DDFileSyncPlugin
{
    [Serializable]
   
    public class DDBackupTrackingTable : TableServiceEntity
    {
        public const string TABLE_NAME = "ddbackuptrackingtable";

       
        /// <summary>
        /// Database Name_PackageId_ProvId
        /// </summary>
//public override string PartitionKey
//{
//  get { return SecUtility.PartitionAndRowKeyEscape(base.PartitionKey); }
//  set { base.PartitionKey = SecUtility.PartitionAndRowKeyEscape(value);}
//}

public static string CreatePartitionKey(string databaseName, string packageId, string provId)
{
    return string.Format("{0}_{1}_{2}", databaseName, packageId, provId);

}
public static string CreateRowKey()
{
    return string.Format("{0}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks);

}
    // To sort the time from newest to oldest
    // <DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks>_EntityType
    // The ticks can be at most 19 digits


     public string BackupFileContainerName {get;set;}
        public string BackupFileBlobName {get;set;}
        public string RoleId {get;set;}
        public DateTime DateBackupWasCreated {get;set;}
        public bool IsCompressed {get;set;}
        public string TriggerType {get;set;}
        public string ProvisioningHive {get;set;}
        public string PackageHive {get;set;}
        public string LocalFilePath { get; set; }

        public DDBackupTrackingTable()
        {


        }

      

    }

    public static class DDBackupTrackingTableUtil
    {
        public static readonly TableStorageHelper TableHelper;


        static DDBackupTrackingTableUtil()
        {
            try
            {
                string storageAccountConnectionString = SyncService.GetConfigValueAsString("com.dynamicdeploy.ddfilesync.DataConnectionString");
                TableHelper = new TableStorageHelper(storageAccountConnectionString);

                //Create only if table did not exist
                if (TableHelper.CreateTable(DDBackupTrackingTable.TABLE_NAME))
                {
                    Trace.TraceInformation("Created Table " + DDBackupTrackingTable.TABLE_NAME);


                }
                else
                {
                    Trace.TraceInformation("Could not create Table " + DDBackupTrackingTable.TABLE_NAME);

                }



            }
            catch (Exception ex)
            {

                Trace.TraceError("DDBackupTrackingTable Init " + ex.Message);
            }

        }
        public static IQueryable<DDBackupTrackingTable> GetLatestDatabaseBackups(string databaseName, string packageId, string provId, MySqlBackupTrigger triggerType, int count)
        {

            string partitionKey = SecUtility.PartitionAndRowKeyEscape( DDBackupTrackingTable.CreatePartitionKey(databaseName, packageId, provId));

            string triggerTypeStr = triggerType.ToString();

            string startRowKey = string.Format("{0:D19}", DateTime.MinValue.Ticks);
            string endRowKey = string.Format("{0:D19}", DateTime.MaxValue.Ticks);
            TableServiceContext tableServiceContext = TableHelper.TableClient.GetDataServiceContext();
            tableServiceContext.IgnoreResourceNotFoundException = true;

            return
                (from entity in
                     tableServiceContext.CreateQuery<DDBackupTrackingTable>(DDBackupTrackingTable.TABLE_NAME)
                 where entity.PartitionKey == partitionKey && entity.RowKey.CompareTo(startRowKey) >= 0
                    && entity.RowKey.CompareTo(endRowKey) <= 0
                 select entity).Take(count);


        }

        public static bool SaveBackupTracking(DDBackupTrackingTable item)
        {
           
            return TableHelper.UpsertEntity(DDBackupTrackingTable.TABLE_NAME, item);

        }
     
    }
}
